Urf. I hate reading code that isn't indented, especially when I don't know what it does.
Code:
/* add the listener to the master set */
FD_SET (listener, &master);
/* keep track of the biggest file descriptor */
fdmax = listener; /* so far, it's this one */
/* loop */
for (;;)
{
/* copy it */
read_fds = master;
if (select (fdmax + 1, &read_fds, NULL, NULL, NULL) == -1)
{
perror ("Server-select() error lol!");
exit (1);
}
printf ("Server-select() is OK...\n");
/*run through the existing connections looking for data to be read*/
for (i = 0; i <= fdmax; i++)
{
if (FD_ISSET (i, &read_fds))
{ /* we got one... */
if (i == listener)
{
/* handle new connections */
addrlen = sizeof (clientaddr);
if ((newfd =
accept (listener, (struct sockaddr *) &clientaddr,
&addrlen)) == -1)
{
perror ("Server-accept() error lol!");
}
else
{
printf ("Server-accept() is OK...\n");
/* add to master set */
FD_SET (newfd, &master);
if (newfd > fdmax)
{ /* keep track of the maximum */
fdmax = newfd;
}
printf ("%s: New connection from %s on socket %d\n",
argv[0], inet_ntoa (clientaddr.sin_addr), newfd);
}
}
else
{
/* handle data from a client */
if ((nbytes = recv (i, buf, sizeof (buf), 0)) <= 0)
{
/* got error or connection closed by client */
if (nbytes == 0)
/* connection closed */
printf ("%s: socket %d hung up\n", argv[0], i);
else
perror ("recv() error lol!");
/* close it... */
close (i);
/* remove from master set */
FD_CLR (i, &master);
}
else
{
/* we got some data from a client*/
for (j = 0; j <= fdmax; j++)
{
/* send to everyone! */
if (FD_ISSET (j, &master))
{
/* except the listener and ourselves */
if (j != listener && j != i)
{
if (send (j, buf, nbytes, 0) == -1)
perror ("send() error lol!");
}
}
Much better . . .
I don't know much about socket programming, but I think a set of sockets is like an array of them. Just thought I'd clear that up at the beginning.
How does it handle new connections? Well . . .
Code:
if (i == listener)
{
/* handle new connections */
addrlen = sizeof (clientaddr);
if ((newfd =
accept (listener, (struct sockaddr *) &clientaddr,
&addrlen)) == -1)
{
perror ("Server-accept() error lol!");
}
else
{
printf ("Server-accept() is OK...\n");
/* add to master set */
FD_SET (newfd, &master);
if (newfd > fdmax)
{ /* keep track of the maximum */
fdmax = newfd;
}
printf ("%s: New connection from %s on socket %d\n",
argv[0], inet_ntoa (clientaddr.sin_addr), newfd);
}
}
The program has opened a listener socket, and when it receives a connection on that one, it must be a new one. It adds it to the list, and there you go.
I make it sound so simple.
[edit] I much prefer this tutorial: http://beej.us/guide/bgnet/output/ht...et.html#listen [/edit]